# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from odoo import api, SUPERUSER_ID

MODULE_ME_NAME = 'l10n_cn_patch'
CHART_TEMPLATE_NAME = 'l10n_cn.l10n_chart_china_small_business'


def _update_account(env, chart_template, company, codes, vals_fn):
    for account_template in chart_template.account_ids.filtered(
            lambda template: template.code in codes):
        acc = env['account.account'].search(
            [('code', '=', account_template.code + '00'),
             ('company_id', '=', company.id)], limit=1)

        vals = vals_fn(account_template)
        acc.write(vals)


def update_account_name(env, chart_template, company):
    # 官方代码 这两个科目的名称弄错了
    codes = ['2241', '2501']
    _update_account(
        env, chart_template, company, codes,
        lambda account_template: {'name': account_template.name})


def update_account_user_type(env, chart_template, company):
    # 1123 预付账款 的类型 由 data_account_type_prepayments
    # 改为 data_account_type_receivable, 才能核销
    # '2501', '2502', '2701', '2711', '2801' 改为 非流动负债
    # 便于做资产负债表
    codes = ['1123', '2501', '2502', '2701', '2711', '2801']
    _update_account(
        env, chart_template, company, codes,
        lambda account_template: {
            'user_type_id': account_template.user_type_id.id,
            'internal_type': account_template.user_type_id.type,
            'reconcile': account_template.reconcile
        })


def _get_chart_template(env):
    chart_template = env.ref(CHART_TEMPLATE_NAME)
    return chart_template


def init_settings(env):
    chart_template = _get_chart_template(env)

    for company in env['res.company'].search([('chart_template_id', '=', chart_template.id)]):
        # 修正 company.transfer_account_id
        # chart_template._set_company_transfer_account(company)

        # 修正 两个科目的名称
        update_account_name(env, chart_template, company)

        # 修正 几个科目的类型
        update_account_user_type(env, chart_template, company)


def load_translations(env):
    chart_template = _get_chart_template(env)
    chart_template.process_coa_translations()


def load_po_overwrite(env):
    module = env['ir.module.module'].search([('name', '=', MODULE_ME_NAME)])
    # odoo13 里 overwrite 参数是在 context 中
    # odoo14 里 overwrite 参数是在 参数 中
    module._update_translations(overwrite=True)


def post_init(cr, registry):
    env = api.Environment(cr, SUPERUSER_ID, {})
    print('post_init in l10n patch 1,', env)
    #
    # 覆盖翻译
    load_po_overwrite(env)
    print('post_init in l10n patch 2,load_po_overwrite ok')

    load_translations(env)
    print('post_init in l10n patch 3,load_translations ok')

    init_settings(env)
    print('post_init in l10n patch 4, init_settings, ok')
